<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <button>上传图片</button>
  <input type="file">
  <hr>
  <img src="./src/assets/images/avatar.jpg" alt="" style="width: 300px; height: 300px" object-fit: cover;>
  <script>
    let btn = document.querySelector('button')
    let input = document.querySelector('input')
    let img = document.querySelector('img')

    btn.addEventListener('click', function () {
      input.click()
    })

    input.addEventListener('change', function () {
      // console.log(input.files)
      if (input.files.length > 0) {
        let fileObj = input.files[0]
        // console.log(fileObj)

        //第一种做法使用URl对象做预览
        // let url = URL.createObjectURL(fileObj)
        // img.src = url
        let fr = new FileReader()
        fr.readAsDataURL(fileObj)
        fr.addEventListener('load', function () {
          img.src = fr.result
        })

      } else { }
    })
  </script>
</body>

</html>